<?php

/**
 * SmartPHP framework
 *
 * @name SmartPHP framework
 * @package SmartPHP
 * @author 费尔 <admin@xuai.cn>
 * @version 3.0
 * @link http://www.SmartPHP.cn
 * @copyright SmartPHP.cn
 * @license <a href="http://www.SmartPHP.cn">SmartPHP</a>
 */

namespace Base;

/**
 * 路由操作
 *
 * @author 费尔 <admin@xuai.cn>
 */
class Route {

    /**
     * 初始路由器
     * @access private
     */
    public static function init() {
        self::initUrl();
    }

    /**
     * URL路由检测（根据PATH_INFO)
     * @access private
     */
    private static function initUrl() {
        $path = self::getPath();
        $depr = Config::get('url.pathinfodepr');
        if ('/' != $depr) {
            $path = str_replace($depr, '/', $path);
        }
        //路由别名
        $array = explode('/', $path);
        //获取控制器名
        $controller = ucfirst(strtolower(strip_tags(!empty(($controller = array_shift($array))) ? $controller : Config::get('controller'))));
        //获取操作名
        $action = strtolower(strip_tags(!empty(($action = array_shift($array))) ? $action : Config::get('action')));
        if (!empty($array)) {
            if (count($array) === 1) {
                defined('APP_VARKEY') or define('APP_VARKEY', array_shift($array));
            } else {
                self::parseVar($array);
            }
        }
        defined('APP_VARKEY') or define('APP_VARKEY', null);
        //执行操作
        if (!preg_match('/^[A-Za-z](\/|\.|\w)*$/', $controller)) {
            self::error('Illegal Controller Name:' . $controller);
        }
        if (!preg_match('/^[A-Za-z](\w)*$/', $action)) {
            self::error('Illegal Action Name:' . $action);
        }
        //控制器名称
        define('APP_CONTROLLER', $controller);
        //项目名称
        define('APP_ACTION', $action);
    }

    /**
     * 解释 Var
     *
     * @access private
     */
    private static function parseVar($url) {
        if (!empty($url)) {
            preg_replace_callback('/(\w+)\/([^\/]+)/', function ($match) use(&$var) {
                $var[strtolower($match[1])] = strip_tags($match[2]);
            }, implode('/', $url));
            if (!empty($var))
                $_GET = array_merge($var, $_GET);
        }
    }

    /**
     * 获取当前请求URL的pathinfo信息（含URL后缀）
     * @access public
     * @return string
     */
    public static function getPathInfo() {
        static $pathinfo = null;
        if (is_null($pathinfo)) {
            if (isset($_GET[Config::get('url.pathinfo')])) {
                $_SERVER['PATH_INFO'] = $_GET[Config::get('url.pathinfo')];
                unset($_GET[Config::get('url.pathinfo')]);
            } elseif (PHP_SAPI == 'cli') {
                $_SERVER['PATH_INFO'] = $_SERVER['argv'][1] ?? '';
            }
            if (!isset($_SERVER['PATH_INFO'])) {
                foreach (Config::get('url.pathinfofetch') as $type) {
                    if (!empty($_SERVER[$type])) {
                        $_SERVER['PATH_INFO'] = (0 === strpos($_SERVER[$type], $_SERVER['SCRIPT_NAME'])) ? substr($_SERVER[$type], strlen($_SERVER['SCRIPT_NAME'])) : $_SERVER[$type];
                        break;
                    }
                }
            }
            $pathinfo = empty($_SERVER['PATH_INFO']) ? '/' : ltrim($_SERVER['PATH_INFO'], '/');
        }
        return $pathinfo;
    }

    /**
     * 当前URL的访问后缀
     * @access public
     * @return string
     */
    public static function ext() {
        return pathinfo(self::getPathInfo(), PATHINFO_EXTENSION);
    }

    /**
     * 获取当前请求URL的pathinfo信息(不含URL后缀)
     * @access public
     * @return string
     */
    public static function getPath() {
        static $path = null;
        if (is_null($path)) {
            $suffix = Config::get('url.htmlsuffix');
            $pathinfo = self::getPathInfo();
            $path = false === $suffix ? $pathinfo : ( $suffix ? preg_replace('/\.(' . ltrim($suffix, '.') . ')$/i', '', $pathinfo) : preg_replace('/\.' . self::ext() . '$/i', '', $pathinfo));
        }
        return $path;
    }

    /**
     * 字符串命名风格转换
     * type 0 将Java风格转换为C的风格 1 将C风格转换为Java的风格
     * @param string  $name 字符串
     * @param integer $type 转换类型
     * @return string
     */
    public static function parseName($name, $type = 0) {
        return $type ? ucfirst(preg_replace_callback('/_([a-zA-Z])/', function ($match) {
                            return strtoupper($match[1]);
                        }, $name)) : strtolower(trim(preg_replace("/[A-Z]/", "_\\0", $name), "_"));
    }

}
